/*
 * Copyright 2010 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alertleon;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

/*
 * The purpose of this queue is to send messages to its listeners at a specified time interval.
 * The reason is that we wanted to be able to batch the sending of the messages so that we would not get spammed with
 * so much alert mail. Also it allows all the messages to be condensed with like messages so messages are not repeated.
 *
 * The following configuration properties are optional for this class:
 *
 * alert.enabled=false (default: false)
 * alert.delay=1 (default: 1 minute)
 */
public class EmailAlertQueue extends AbstractAlertQueue {

    private final Set<String> messages = new LinkedHashSet<String>();

    public EmailAlertQueue(AlertConfiguration configuration) {
        super(configuration);
    }

    public synchronized void addAlert(String message) {
        messages.add(message);
    }

    public void sendAlerts() {
        if (messages.isEmpty()) {
            return;
        }

        Set<String> messagesCopy;

        synchronized (this) {
            messagesCopy = new LinkedHashSet<String>(messages);
            messages.clear();
        }

        for (AlertListener listener : getListeners()) {
            listener.handleAlerts(Collections.unmodifiableSet(messagesCopy));
        }
    }
}